// pages/guidanceStudy/latest_resource/index.js

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    resource_info:{},
    user_info:{},
    ratio: app.phoneInfo.ratio,
    alertType: false,
    second: 10,
    submitType: true,
    disabled: true,
    showDialog: false,
    canvasHeight: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '拼命加载中...',
      icon: 'none'
    });
    
    wx.request({
      url: app.globalData.url + 'c=newActivity&m=get_detail&user_id=' + wx.getStorageSync('user_id') + '&resource_id=' + options.id,
      success: res => {
        res = res.data;
        if (res.status === 200) {
          wx.setNavigationBarTitle({
            title: res.data.resource_info.title
          })
          this.setData({
            'resource_info': res.data.resource_info,
            'user_info': res.data.user_info
          })
        }

        wx.hideLoading();
      },
      fail: res => {
        wx.hideLoading();
        wx.showToast({
          title: res.msg
        });
      },
    });
  },


  /**
   * 获取图片
   */
  getImage: function () {
    wx.getImageInfo({
      src: this.data.resource_info.post_image,
      success: img1 => {
        //缩放比例
        var ratio = 620 / img1.width
        this.setData({
          'canvasHeight': (img1.height + 140) * ratio
        })
        wx.getImageInfo({
          src: 'https://zsy.api.oucnet.com/statics/zsy/resourse/img/bg-footer.png',
          success: img2 => {
            wx.getImageInfo({
              src: this.data.user_info.wx_head,
              success: img3 => {
                if (this.data.resource_info.url) {
                  wx.getImageInfo({
                    src: this.data.resource_info.qr_code_url,
                    success: img4 => {
                      this.drawImg(img1, img2, img3, img4);
                    },
                    fail: (err) => {
                      wx.hideLoading();
                    }
                  })
                }else{
                  this.drawImg(img1, img2, img3);
                }
              },
              fail: () => {
                wx.hideLoading();
              }
            })
          },
          fail: () => {
            wx.hideLoading();
          }
        })
      },
      fail: () => {
        wx.hideLoading();
      }
    });
  },

  /**
   * 保存分享福利券
   */
  submit: function () {
    wx.showLoading({
      title: '保存中',
    });
    this.getImage();
  },
  /**
   * canvas绘制
   */
  drawImg: function (img1, img2, img3, img4) {
    var context = wx.createCanvasContext('share');
    context.fillStyle = '#F1F1F1';
    context.shadowColor = "#E5E5E5";
    context.fillRect(0, 0, 620 / this.data.ratio, this.data.canvasHeight / this.data.ratio);

    // let canvasWidthPx = 620 / this.data.ratio;
    // let canvasHeightPx = img1.height / this.data.ratio;
    context.drawImage(img1.path, 0, 0, 620 / this.data.ratio, img1.height * 620 / img1.width / this.data.ratio);
    context.drawImage(img2.path, 0, (this.data.canvasHeight-140)/this.data.ratio, 620 / this.data.ratio, 140 / this.data.ratio);

    context.save();
    context.beginPath();
    context.arc((144 - 65) / this.data.ratio, (this.data.canvasHeight - 67) / this.data.ratio, 50 / this.data.ratio, 0, Math.PI * 2, false);
    context.setStrokeStyle('#e0e0e0');
    context.stroke();
    context.clip();
    context.drawImage(img3.path, (94 - 65) / this.data.ratio, (this.data.canvasHeight - 117) / this.data.ratio, 100 / this.data.ratio, 100 / this.data.ratio);
    context.restore();

    context.setFontSize(32 / this.data.ratio);
    context.setTextAlign('left');
    context.setFillStyle('#ffffff');
    context.fillText(this.data.user_info.agent_name, (224 - 65) / this.data.ratio, (this.data.canvasHeight - 75) / this.data.ratio);
    context.setFontSize(24 / this.data.ratio);
    context.fillText('求学圆梦行动特邀·招生顾问', (224 - 65) / this.data.ratio, (this.data.canvasHeight - 37) / this.data.ratio);

    if (img4) {
      let img4X = 490 / this.data.ratio;
      let img4Y = (this.data.canvasHeight-121) / this.data.ratio;
      context.drawImage(img4.path, img4X, img4Y, 100 / this.data.ratio, 100 / img4.width * img4.height / this.data.ratio);
    }

    context.draw(false, this.getTempFilePath);
  },

  /**
   * 获取临时路径
   */
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'share',
      success: res => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
        this.saveImageToPhotosAlbum();
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  /**
   * 保存相册
   */
  saveImageToPhotosAlbum: function () {
    wx.hideLoading();
    var that = this;
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.save();
            },
            fail(err) {
              console.log(err);
              that.setData({
                'showDialog': true
              })
            }
          })
        } else {
          that.save();
        }
      }
    })
  },

  save: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {
        this.setData({
          alertType: true
        })
        this.waitTime();
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },

  /**
   * 倒计时
   */
  waitTime: function () {
    let s = this.data.second;
    var timer = setInterval(() => {
      s--;
      if (s == 0) {
        clearInterval(timer);
        timer = null;
        this.setData({
          submitType: false
        })
      } else {
        this.setData({
          second: s
        });
      }
    }, 1000);

    // setTimeout(this.waitTime, 1000);
  },

  /**
   * 关闭弹窗
   */
  closeAlert: function () {
    this.setData({
      alertType: false,
      submitType: true,
      sverType: true,
      second: 10
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})